package com.pysrc.base.service.impl;

import com.pysrc.base.entity.MateStoreMapping;
import com.pysrc.base.entity.Materiel;
import com.pysrc.base.mapper.MateStoreMappingMapper;
import com.pysrc.base.service.MateStoreMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * @ClassName:
 * @Auther L.Chen
 * @CreateDate
 * @Description TODO
 */
@Service
public class MateStoreMappingServiceImpl extends BaseServiceImpl<MateStoreMapping> implements MateStoreMappingService {
    private MateStoreMappingMapper mapper;

    @Autowired
    private void init(MateStoreMappingMapper mapper) {
        this.mapper = mapper;
        super.mapper = mapper;
    }

    /**
     * 库存调拨
     * @param mapping
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public MateStoreMapping update(MateStoreMapping mapping) throws Exception {
        if (mapping.getMateId() == null
                || mapping.getStorId() == null
                || mapping.getMateNum() ==null
                ) {
            return null;
        }
        MateStoreMapping msm = new MateStoreMapping();
        msm.setMateId(mapping.getMateId());
        msm.setStorId(mapping.getStorId());
        List<MateStoreMapping> mappings = mapper.select(msm);
        if(mappings==null||mappings.size()==0){
            // 插入新行
            if(mapping.getMateNum().compareTo(new BigDecimal(0))>0){ // 数量必须大于0
                return mapper.insert(mapping)==0?null:mapping;
            }else{
                throw new Exception("插入库存数量小于0");
            }
        }else{
            // 入库或者出库
            MateStoreMapping tmp = mappings.get(0);
            BigDecimal mateNum = tmp.getMateNum();
            mateNum = mateNum.add(mapping.getMateNum());
            int compare = mateNum.compareTo(new BigDecimal(0));
            if(compare ==0){
                // 库存为0 删除记录
                mapper.deleteByPrimaryKey(tmp.getMsmId());
                return null;
            }else if(compare<0){
                throw new Exception("库存不足");
            }else{
                tmp.setMateNum(mateNum);
                return 0==mapper.updateByPrimaryKey(tmp)?null:tmp;
            }
        }
    }
}
